/**
 * Copyright (c) 2016-2020, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.addon.servicebulletins.controller;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jpress.addon.servicebulletins.model.JpressAddonServicebulletins;
import io.jpress.addon.servicebulletins.service.JpressAddonServicebulletinsService;

import io.jpress.model.User;

import io.jpress.web.base.TemplateControllerBase;




@RequestMapping(value = "/servicebulletins")
public class ServicebulletinsController extends TemplateControllerBase {

    @Inject
    private JpressAddonServicebulletinsService service;

    public void index() {

        if(getLoginedUser()==null){
            redirect("/user/login");
            return;
        }

        setMenuActive(menu -> {
            if (menu.isUrlEquals("/servicebulletins/index")) {
                return true;
            }
            return false;
        });

        render("servicebulletins.html");
    }

    //详情
    public void details() {

        setMenuActive(menu -> {
            if (menu.isUrlEquals("/servicebulletins/details")) {
                return true;
            }
            return false;
        });

        Integer id = getParaToInt("id");
        JpressAddonServicebulletins jpressAddonServicebulletins = service.findById(id);
        setAttr("servicebulletins", jpressAddonServicebulletins);
        render("servicebulletins_details.html");
    }

    public void getjson(){
        User loginedUser = getLoginedUser();
        if(loginedUser==null){
            renderJson(Ret.fail());
            return;
        }

        String model = getPara("model");
        SqlPara sqlPara = new SqlPara();

        String sql =  "SELECT a.* FROM addon_servicebulletins a LEFT JOIN addon_servicebulletins_user b on b.servicebulletins_id = a.id WHERE user_id = "+loginedUser.getId();

        if(model!=null) {
            sql += " and model = ?";
            sqlPara.addPara(model);
        }
        sqlPara.setSql(sql+" order by release_date desc");
        Page<Record> paginate = Db.paginate(1, 8, sqlPara);
        renderJson(Ret.ok("slist", paginate));

    }

}
